package com.kaibes.orm.spring.jdbc;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import com.kaibes.orm.core.core.Mapper;
import com.kaibes.orm.core.core.SqlRunner;
import com.kaibes.orm.core.dialect.Dialect;

public class BaseMapper<E> extends Mapper<E> {
    
    private DataSourceTransactionManager transactionManager;
    private TransactionDefinition transactionDefinition;
    
    public BaseMapper(Dialect dialect, SqlRunner sqlRunner, DataSourceTransactionManager transactionManager, TransactionDefinition transactionDefinition) {
        super(dialect, sqlRunner);
        createEntityClass();
        this.transactionManager = transactionManager;
        this.transactionDefinition = transactionDefinition;
    }
    
    @Override
    protected Object openTransaction() {
        return transactionManager.getTransaction(transactionDefinition);
    }

    @Override
    protected void commit(Object transaction) {
        TransactionStatus transactionStatus = (TransactionStatus) transaction;
        if (transactionStatus.isNewTransaction()) {
            transactionManager.commit(transactionStatus);//提交
        }
    }

    @Override
    protected void rollback(Object transaction) {
        TransactionStatus transactionStatus = (TransactionStatus) transaction;
        if (transactionStatus.isNewTransaction()) {
            transactionManager.rollback(transactionStatus);
        }
    }
    
    @SuppressWarnings("unchecked")
    protected void createEntityClass() {
        if (getTableColumn() == null && getClass() != BaseMapper.class) {
            Type superClass = getClass().getGenericSuperclass();
            Class<E> entityClass = (Class<E>) ((ParameterizedType) superClass).getActualTypeArguments()[0];
            setEntityClass(entityClass);
        }
    }

}
